package handel

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"logi-deliv/cache"
	"logi-deliv/model"
	"strconv"
	"time"
)

func PeopleAdd(c *gin.Context) {
	people_code := c.PostForm("people_code")
	people_name := c.PostForm("people_name")
	data := model.People{
		PeopleCode: people_code,
		PeopleName: people_name,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_address := c.PostForm("order_address")
	people_id, _ := strconv.Atoi(c.PostForm("people_id"))
	data := model.Order{
		OrderCode:    order_code,
		OrderAddress: order_address,
		PeopleId:     people_id,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func PeopleOrderList(c *gin.Context) {
	/*
			SELECT
		  orders.order_code as OrderCode,
		  orders.order_address as OrderAddress,
		  peoples.people_code as PeopleCode,
		  peoples.people_name as PeopleName
		FROM
		  orders
		  LEFT JOIN peoples ON orders.people_id = peoples.id
	*/
	var list []model.List
	redis_key := "order_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").
			Select(
				"orders.order_code as OrderCode",
				"orders.order_address as OrderAddress",
				"peoples.people_code as PeopleCode",
				"peoples.people_name as PeopleName",
			).
			Joins("LEFT JOIN peoples ON orders.people_id = peoples.id").
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": list,
	})
}
func PeopleOrderFind(c *gin.Context) {
	id := c.Query("id")
	var list model.List
	redis_key := "order_find_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").
			Select(
				"orders.order_code as OrderCode",
				"orders.order_address as OrderAddress",
				"peoples.people_code as PeopleCode",
				"peoples.people_name as PeopleName",
			).
			Joins("LEFT JOIN peoples ON orders.people_id = peoples.id").
			Where("orders.id=?", id).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": list,
	})
}
